<!-- 签到二维码课程列表 -->
<script setup lang="ts">
import { useLoadMore } from 'vue-request'
import { fetchCourseScheduleAPI } from '@/apis/fetchCourseSchedule'
import { useUserInfoStore } from '@/store/userInfo'

const router = useRouter()
const userInfoStore = useUserInfoStore()

// 班级 id
const classId = ref('')

// 分页列表数据
const { dataList, loading, loadingMore, noMore, loadMore, refresh } = useLoadMore<LoadMoreData<Course>>(
  fetchCourses,
  { isNoMore: d => d?.list.length === d?.total },
)

// “加载更多”的状态
const loadMoreStatus = computed(() => {
  if (loadingMore.value)
    return 'loading'
  else if (noMore.value)
    return 'nomore'
  else
    return 'loadmore'
})

onLoad((options) => {
  if (options && options.class_id) {
    classId.value = options.class_id
    refresh()
  }
  else { uni.showToast({ title: '页面加载错误：未获取到班级id', icon: 'none' }) }
})
onReachBottom(() => loadMore())

/**
 * @description 分页服务函数
 */
async function fetchCourses(d?: LoadMoreData<Course>): Promise<LoadMoreData<Course>> {
  // 缺少必要参数，先不执行
  if (!classId.value) {
    return {
      list: [],
      page: 0,
      total: 0,
    }
  }

  // 当前页数
  const _page = d?.page ? d.page + 1 : 1

  const res = await fetchCourseScheduleAPI({
    id: classId.value,
    page: _page.toString(),
    limit: '10',
  }, userInfoStore.userInfo!.token!)

  return {
    list: res.data?.data.data || [],
    page: _page,
    total: res.data?.data.total || 9999,
  }
}

function handleTapCardButton(course: Course) {
  router.push({
    name: 'qrcode',
    params: { c: JSON.stringify(course) },
  })
}
</script>

<template>
  <Spacer height="20" />
  <uv-list :custom-style="{ background: 'transparent' }">
    <view v-for="course in dataList" :key="course.id" :style="{ borderRadius: '20rpx', marginBottom: '20rpx' }">
      <view class="rounded-20rpx bg-white card-shadow">
        <RecordItem
          :picture="course.images!"
          :title="course.title || '未知标题'"
          :teacher="course.teacher_name || '未知'"
          :org="course.place || '未知'"
          :created-at="course.start_time || '未知时间'"
          hide-shadow
          show-divider
        />
        <Divider width="650" />
        <view class="flex flex-row-reverse px-25rpx py-20rpx">
          <button class="h-60rpx w-160rpx flex items-center justify-center rounded-full bg-#0037AE text-24rpx text-white font-semibold leading-32rpx" hover-class="bg-#3266D9" @tap="handleTapCardButton(course)">
            签到二维码
          </button>
        </view>
      </view>
    </view>
    <!-- 加载更多 -->
    <uv-load-more v-if="dataList.length > 3" :status="loadMoreStatus" @loadmore="loadMore" />
  </uv-list>
  <Spacer height="80" />
  <PageDefault v-if="dataList.length === 0">
    暂无课程安排
  </PageDefault>
  <uv-loading-page :loading="loading && !loadingMore" loading-text="加载中..." font-size="28rpx" loading-mode="spinner" />
</template>

<route lang="yaml">
name: 'managerQRCodeCourseList'
style:
  navigationBarTitleText: '签到二维码'
</route>
